/**
 * 
 */

package com.shy.portal.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shy.base.controller.AbsController;
import com.shy.base.util.BeanUtil;
import com.shy.base.vo.AppConstants;
import com.shy.base.vo.EasyuiPagerVo;
import com.shy.base.vo.PagerFilter;
import com.shy.portal.entity.Role;
import com.shy.portal.service.RoleService;
import com.shy.portal.service.UserService;
import com.shy.portal.vo.UserRoleVo;

/**
 * Title: RoleController Description:角色信息管理控制器 Company:ipebg
 * 
 * @author H2013788
 */
@Controller
@RequestMapping("/role")
public class RoleController extends AbsController {

	/**
     * log
     */
	private Logger logger = LogManager.getLogger(this.getClass());
    
    /**
     * service层
     */
    @Resource
    private RoleService roleService;
    
    /**
     * service层
     */
    @Resource
    private UserService userService;

    /**
     * 请求角色列表页面
     * 
     * @return 角色列表页面
     * @author H2013788
     * @date 2017/10/6下午1:52:52
     */
    @RequestMapping("/list_page")
    public String showRoleListPage() {
        return "portal/role_list";
    }

    /**
     * 異步加载角色列表数据
     * 
     * @param role
     *            查询條件
     * @param page 頁
     * @param rows 行
     * @author H2013788
     * @date 2017/10/6下午1:55:58
     */
    @RequestMapping("/list_data")
    public void loadRoleList(Role role, Integer page, Integer rows, HttpServletResponse response) {
        PagerFilter pagerFilter = getPageable(rows == null ? 10L : rows);
        pagerFilter.setPagePer(null == page ? 1 : page);
        LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
        orderby.put("id", "asc");
        pagerFilter.setOrderby(orderby);
        pagerFilter = roleService.listByPager(role, null, pagerFilter);
        writeResponse(new StringBuffer(gsonDateTimeExpose.toJson(new EasyuiPagerVo(pagerFilter))), response);
    }

    /**
     * 角色預编辑，按照ID查询角色信息
     * 
     * @param id 角色ID
     * @author H2013788
     * @date 2017/10/6下午1:57:19
     */
    @RequestMapping("/edit_role")
    public void editRole(Integer id, HttpServletResponse response) {
        if (null != id) {
            Role role = roleService.getById(id);
            writeResponse(new StringBuffer(gsonDateTimeExpose.toJson(role)), response);
        } else {
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.GET_OBJECT_NULL), response);
        }
    }

    /**
     * 保存角色信息，用於新增或编辑角色
     * 
     * @param role 角色實体
     * @author H2013788
     * @date 2017/10/6下午1:58:54
     */
    @RequestMapping("/save_role")
    public void saveRole(Role role, HttpServletResponse response) {
        if (null == role) {
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
        } else {
            try {
                if (null != role.getId()) {
                    role.setUpdateTime(new Date());
                    Role old = roleService.getById(role.getId());
                    BeanUtil.merge(old, role);
                    roleService.update(old);
                } else {
                    role.setCreateTime(new Date());
                    roleService.save(role);
                }
                respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.SAVE_SUCCESS), response);
            } catch (Exception e) {
                e.printStackTrace();
                respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.SAVE_ERROR), response);
                logger.error(AppConstants.configMap.get(AppConstants.SAVE_ERROR) + e);
            }
        }

    }

    /**
     * 刪除指定角色
     * 
     * @param id 角色ID
     * @author H2013788
     * @date 2017/10/6下午1:59:18
     */
    @RequestMapping("/delete_role")
    public void deleteRole(Integer id, HttpServletResponse response) {
        try {
            if (null != id) {
                roleService.deleteById(id);
                respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.OPERATE_SUCCESS), response);
            } else {
                respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.OPERATE_ERROR), response);
            logger.error(AppConstants.configMap.get(AppConstants.DELETE_ERROR) + e);
        }
    }

    /**
     * ajax返回角色列表
     * 
     * @param userId
     *            当前要配置角色的用户
     * @param response 反饋
     * @author H2013788
     * @date 2017/11/17下午4:33:34
     */
    @RequestMapping("/find_all_role")
    public void findRoleList(Integer userId, HttpServletResponse response) {
        List<Role> allRoleList = roleService.findAll();
        List<Role> userRolelist = userService.listRoleByUserId(userId);
        Gson gson = new Gson();
        writeResponse(
                new StringBuffer(gson.toJson(buildUserRoleList(allRoleList, userRolelist))),
                response);
    }

    /**
     * 組裝角色列表，同时標注当前用户已具有的角色
     * 
     * @param allRoleList 所有角色列表
     * @param userRolelist 用户角色列表
     * @return 角色列表
     * @author H2013788
     * @date 2017/11/17下午4:44:49
     */
    private List<UserRoleVo> buildUserRoleList(List<Role> allRoleList, List<Role> userRolelist) {
        List<UserRoleVo> list = new ArrayList<>();
        for (Role role : allRoleList) {
            UserRoleVo userRoleVo = new UserRoleVo();
            userRoleVo.setRoleId(role.getId());
            userRoleVo.setRoleName(role.getRoleName());
            userRoleVo.setChecked(false);
            for (Role role1 : userRolelist) {
                if (role1.getId().intValue() == role.getId().intValue()) {
                    userRoleVo.setChecked(true);
                }
            }
            list.add(userRoleVo);
        }
        return list;
    }

}
